<template>
  <div class="map">
    <header>
      <van-icon name="arrow-left" @click="$router.go(-1)" />
      <h3>地图找房</h3>
      <i></i>
    </header>
    <main>
      <baidu-map class="map" :center="{ lng: 116.404, lat: 39.915 }" :zoom="7">
        <bm-marker
          :position="{ lng: 116.404, lat: 39.915 }"
          :dragging="true"
          animation="BMAP_ANIMATION_BOUNCE"
        >
          <bm-label
            content="mapList"
            :labelStyle="{ color: 'red', fontSize: '14px' }"
            :offset="{ width: -35, height: 30 }"
          />
          <!-- 比例尺 -->
          <bm-scale anchor="BMAP_ANCHOR_BOTTOM_LEFT"></bm-scale>
          <!-- 缩放 -->
          <bm-navigation anchor="BMAP_ANCHOR_TOP_LEFT"></bm-navigation>
        </bm-marker>
      </baidu-map>
    </main>
  </div>
</template>

<script>
import axios from "axios";
import Toast from "vant";
import { getCurrentCity, API } from "../../utils/map";
export default {
  data() {
    return {
      mapList: {},
    };
  },
  created() {
    this.getMap();
    this.initMap();
  },
  mounted() {
    this.Map();
  },
  methods: {
    Map() {
      const BMap = window.BMap;
      //存储地图实例
      let map = null;
      var initMap = async () => {
        const { label, value } = await getCurrentCity();
        //实例化出来地图对象;
        map = new BMap.Map("container");
        var myGeo = new BMap.Geocoder();
        myGeo.getPoint(
          label,
          async (point) => {
            if (point) {
              //设置中心点坐标;
              map.centerAndZoom(point, 11);
              //添加一个平移缩放的控件;
              map.addControl(new BMap.NavigationControl());
              //添加一个比例尺的控件;
              map.addControl(new BMap.ScaleControl());

              //去添加覆盖物---添加一些标注;
              renderOverlays(value);
            }
          },
          label
        );
        map.addEventListener("movestart", () => {
          setLoaded(false);
        });
      };
      //添加覆盖物的方法
      const renderOverlays = async (id) => {
        //覆盖物多少取决于请求了多少条数据;
        Toast.loading("加载中", 0, null, false);
        const res = await API.get("/area/map", {
          params: {
            id,
          },
        });
        //把toast关闭掉
        Toast.hide();
        //专门写一个方法去获取缩放的级别以及覆盖物的类型;
        const { type, nextLevel } = getTypeAndZoom();
        //获取完缩放 级别和类型之后----可以写一个方法去创建覆盖物
        res.data.body.forEach((item) => {
          createOverlays(type, nextLevel, item);
        });
      };
      const getTypeAndZoom = () => {
        //获取一下当前地图的缩放级别;
        const curZoom = map.getZoom();
        let type, nextLevel;
        if (curZoom >= 10 && curZoom < 12) {
          type = "circle";
          nextLevel = 13;
        } else if (curZoom >= 12 && curZoom < 14) {
          type = "circle";
          nextLevel = 15;
        } else if (curZoom >= 14 && curZoom < 16) {
          type = "rect";
        }
        return {
          type,
          nextLevel,
        };
      };
      const createOverlays = (type, nextLevel, item) => {
        const {
          coord: { latitude, longitude },
          label,
          count,
          value,
        } = item;
        //创建中心点坐标;
        var point = new BMap.Point(longitude, latitude);
        if (type === "rect") {
          //创建长方形的覆盖物;
          createRect(point, label, count, value);
        } else {
          //创建圆形覆盖物;
          createCircle(point, label, count, value, nextLevel);
          //在点击事件里面----
        }
      };
      const createCircle = (point, areaName, count, id, level) => {
        const opts = {
          //坐标
          position: point,
          //偏移量;
          offset: new BMap.Size(-35, -35),
        };
        //创建文本标注对象;
        const label = new BMap.Label("", opts);
        //通过setcontent来设置html内容;
        label.setContent(`
          <div class="${styles.bubble}">
             <p class="${styles.name}">${areaName}</p>
             <p>${count}套</p>
          </div>
        `);
        //设置样式
        label.setStyle(labelStyle);
        //给覆盖物上 添加点击事件;
        label.addEventListener("click", () => {
          //就调用renderOverlays这个方法，去获取数据并创建下一级的覆盖物;
          renderOverlays(id);
          //放大地图;
          map.centerAndZoom(point, level);
          //清除覆盖物;
          setTimeout(() => {
            map.clearOverlays();
          }, 0);
        });
        //把覆盖物添加到地图中;
        map.addOverlay(label);
      };
      const createRect = (point, areaName, count, id) => {
        const opts = {
          position: point,
          offset: new BMap.Size(-50, -28),
        };
        const label = new BMap.Label("", opts);
        label.setContent(`
        <div class="${styles.rect}">
        <span class="${styles.housename}">${areaName}</span>
        <span class="${styles.housenum}">${count}</span>
        </div>
       `);
        //
        label.setStyle(labelStyle);
        label.addEventListener("click", (e) => {
          //小区点击之后----让地图位移到点击的中心点;
          //在移动端怎么去获取手指点击的位置;
          const { clientX, clientY } = e.changedTouches[0];
          //点击哪个就把中心位置让给哪个;
          const x = window.innerWidth / 2 - clientX;
          const y = window.innerHeight / 2 - clientY;
          map.panBy(x, y);

          //获取这个小区下面的房源列表
          getCommitHouse(id);
        });

        map.addOverlay(label);
      };

      const getCommitHouse = async (id) => {
        Toast.loading("加载加载再加载...", 0, null, false);
        //获取小区下面的房源列表;
        const res = await API.get("/houses", {
          params: {
            cityId: id,
          },
        });
        Toast.hide();
        setList(res.data.body.list);
        setLoaded(true);
      };
      const renderHouseList = () => {
        return list.map((item) => {
          return <HomeItem key={item.houseCode} {...item}></HomeItem>;
        });
      };
    },
    getMap() {
      axios.get("/area/map?id=AREA%7C88cff55c-aaa4-e2e0").then((res) => {
        this.mapList = { ...res.data.body };
        console.log(this.mapList);
        console.log(res, "map");
      });
    },
  },
};
</script>

<style lang='scss' scoped>
.map {
  width: 100%;
  height: 100%;
  position: absolute;
  header {
    width: 100%;
    height: 1rem;
    border-bottom: 1px solid #eee;
    background-color: #f6f5f6;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 0.3rem;
    h3 {
      font-weight: normal;
    }
  }
}
.baidumap {
  width: 1000px;
  height: 500px;
  border: 1px solid red;
  position: absolute;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  margin: auto;
  border-radius: 50%;
}

/* 去除百度地图版权那行字 和 百度logo */
.baidumap > .BMap_cpyCtrl {
  display: none !important;
}
.baidumap > .anchorBL {
  display: none !important;
}
</style>